import { timeFormat } from '/js/util/time.js'

let template = {
  name: 'user',
  template: '',
  data() {
    return {
      loading: false,
      userForm: { name: '', password: '' },
      userFormRules: {
        name: [{ required: true, message: '请输入' }],
        password: [{ required: true, message: '请输入' }],
      },
      findUserParam: { name: '' },
      userList: [],
      addUpdateDialogVisible: false,
      userDialogTitle: '添加用户',
      selectUser: {},
    }
  },
  mounted() {
    this.getUsers()
  },
  methods: {
    timeFormat,
    addUpdateDialogShow() {
      this.addUpdateDialogVisible = true
      this.userDialogTitle = '添加用户'
    },
    search() {
      if (this.findUserParam.name) {
        this.getUsers(this.findUserParam.name)
      } else {
        this.getUsers()
      }
    },
    getUsers(name = '') {
      let url = '/user/find'
      if (name) {
        url += `?name=${name}`
      }

      this.loading = true
      Http(url)
        .then((res) => {
          if (res.code === 200) {
            this.userList = res.data
          } else {
            ElMessage.error('获取失败')
          }
          this.loading = false
        })
        .catch((err) => (this.loading = true))
    },
    addUser() {
      if (this.userDialogTitle === '更新信息') {
        return this.updateUser()
      }

      this.$refs.userRef
        .validate()
        .then(() => {
          fetch('/user/add', {
            method: 'post',
            body: JSON.stringify(this.userForm),
            headers: {
              'Content-Type': 'application/json',
            },
          })
            .then((response) => {
              if (response.status > 300) {
                throw response
              }
              return response.json()
            })
            .then((res) => {
              if (res.code === 200) {
                this.getUsers()
                this.addUpdateDialogVisible = false
                ElMessage.success(res.message)
              } else {
                ElMessage.error(res.message)
              }
            })
            .catch((err) => {
              ElMessage.err(err)
            })
        })
        .catch((err) => {})
    },
    editUser(row) {
      this.addUpdateDialogVisible = true
      this.userDialogTitle = '更新信息'
      this.selectUser = row
      this.userForm.name = row.name
      this.userForm.password = row.password
    },
    updateUser() {
      this.$refs.userRef
        .validate()
        .then(() => {
          fetch('/user/update', {
            method: 'post',
            body: JSON.stringify({
              id: this.selectUser.id,
              ...this.userForm,
            }),
            headers: {
              'Content-Type': 'application/json',
            },
          })
            .then((response) => {
              if (response.status > 300) {
                throw response
              }
              return response.json()
            })
            .then((res) => {
              if (res.code === 200) {
                this.getUsers()
                this.addUpdateDialogVisible = false
                ElMessage.success(res.message)
              } else {
                ElMessage.error(res.message)
              }
            })
            .catch((err) => {
              ElMessage.error(err)
            })
        })
        .catch((err) => {})
    },
    deleteUser(id) {
      let url = '/user/delete'
      fetch(url, {
        method: 'post',
        body: JSON.stringify({ id }),
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then((res) => res.json())
        .then((res) => {
          if (res.code === 200) {
            this.getUsers()
            ElMessage.success('删除成功')
          } else {
            ElMessage.error('删除失败')
          }
        })
        .catch((err) => ElMessage.error('请求失败'))
    },
  },
}

export default {
  async load() {
    return fetch(`${config.RP}/html/route/user/user.html`)
      .then((res) => res.text())
      .then((html) => {
        template.template = html
        window.app.component('user', template)
      })
  },
}
